package top.lethelh.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author lh
 * @date 2021/11/24 9:19 下午
 * @desc TCP 客户端
 */
public class TCPClient {
    public static void main(String[] args) {
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", 65000);
            try (OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream()) {
                os.write(new String("Hello World!").getBytes(StandardCharsets.UTF_8));
                int ch = 0;
                byte[] buff = new byte[1024];
                ch = is.read(buff);
                String text = new String(buff, 0, ch);
                System.out.println(text);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
